

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Queue;
import java.util.Scanner;


public class DataServer extends Thread{
	private String hostName;
	private int port;
	private int serverPort;
	public Queue<String> queue;
	ServerSocketChannel server;
	
	public DataServer(int serverPort) throws IOException{
		this.serverPort = serverPort;
		this.server = ServerSocketChannel.open();
		this.server.socket().bind(new InetSocketAddress(serverPort));
		//startHostCommunication();
	}
	
	public DataServer(String hostName, int port, int serverPort){
		
	}

	private void startHostCommunication() throws IOException {
		SocketChannel clientSocket = server.accept();
		System.out.println("HERE*******");
		while(!clientSocket.isConnected()){
			System.out.println("waiting to connect");
		}		
	}

	private void startControlServerCommunication(String hostName, int port, int serverPort) {
		new ControlServerCommunication(hostName, port, serverPort).start();		
	}
	
	public void run(){
		try{
			System.out.println("Initiating server...");
			System.out.println("Please enter control server destination: ");
			Scanner sc = new Scanner(System.in);
			String line = sc.nextLine();
			String[] args = line.split(" ");
			if(args.length != 2){
				System.err.println("Usage error: ");
				System.exit(0);
			}
			this.hostName = args[0];
			this.port = Integer.parseInt(args[1]);
			System.out.println("Starting control server connection...");
			new ControlServerCommunication(hostName, port, serverPort).start();
			new HostCommunication(server).start();
			/*SocketChannel clientSocket = server.accept();	
			System.out.println("HERE*******");
			while(!clientSocket.isConnected()){
				System.out.println("waiting to connect");
			}*/
			
		}catch(Exception e){
		
				
		}
	}



	public static void main(String args[]){
		
		if(args.length != 1){
			System.err.println("Usage: java DataServer <port>");
			System.exit(0);
		}
		
		try {
			new DataServer(Integer.parseInt(args[0])).start();
			
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}
